package com.xjtu.platform.user.admin.statistics;

import com.xjtu.platform.common.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @创建人 MBY381
 * @创建时间 2022/7/6 19:55
 * @描述 暂无
 */


@RestController
@RequestMapping("/stat")
public class StatAPI {

    @Resource
    private StatService statService;


    @RequestMapping(value = "/getItemList", method = RequestMethod.GET)
    public Result getItemList() {
        try {
            List<String> list = statService.getItemList();
            return Result.success("查询所有项目成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_BUSINESS, "系统错误！");
        }
    }

    @RequestMapping(value = "/getVisitXlsFile", method = RequestMethod.GET)
    public synchronized void getVisitXlsFile(@RequestParam String visit_id, HttpServletResponse response) throws IOException {
        String filePath = statService.getFileName(visit_id);
        if (filePath == null || visit_id == null) {
            throw new RuntimeException("信息缺失");
        }
        boolean exists = new File(filePath).exists();
        System.out.println("结案报告文件" + filePath + " " + exists);
        try {
            if (exists) {
                InputStream in = new FileInputStream(filePath);
                OutputStream out = response.getOutputStream();
                byte[] b = new byte[10240];
                int len = -1;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                System.out.println("正在写入文件");
                out.flush();
                out.close();
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/getStat", method = RequestMethod.GET)
    public Result getStat() {
        try {
            StatDto statDto = statService.getStat();
            return Result.success("查询系统数据成功",statDto);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_SYS,"系统错误");
        }
    }

    @RequestMapping(value = "/getFileName",method = RequestMethod.GET)
    public Result getName(@RequestParam String visit_id){
        try {
            String fileName=statService.getFileName(visit_id);
            return Result.success("文件查询成功",fileName.substring(fileName.lastIndexOf('/')+1,fileName.length()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_SYS,"系统错误！");
        }

    }


}
